﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using Hxsoft.AppV1;

namespace Hxsoft.AppV1.Module
{
    public partial class KeywordForLink:ICreator
    {
    }
	/// <summary>
    /// KeywordForLinks 类。
    /// </summary>
    public static partial class KeywordForLinks
    {
        public const string INFO_TYPE = "KeywordForLink";		// 信息的类别代码



        #region GetItem
        /// <summary>
        /// 根据标识获取指定的。
        /// </summary>
        /// <param name="o">集合。</param>
        /// <param name="id">获取的标识 Id。</param>
        /// <returns>获取的信息项。</returns>
        public static KeywordForLink GetItem(this System.Data.Linq.Table<KeywordForLink> o, int id)
        {
            return o.SingleOrDefault(p => p.Id == id);
        }

        /// <summary>
        /// 根据标识获取指定的。
        /// </summary>
        /// <param name="id">获取的标识 Id。</param>
        /// <returns>获取的信息项。</returns>
        public static KeywordForLink GetItem(int id)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            dc.ObjectTrackingEnabled = false;
            return dc.KeywordForLinks.GetItem(id);
        }
        #endregion



        #region Exists
        /// <summary>
        /// 验证指定的是否已经存在。
        /// </summary>
        /// <param name="o">集合。</param>
        /// <param name="id">验证的标识 Id。</param>
        /// <returns>布尔值表示指定的是否已经存在。</returns>
        public static bool Exists(this System.Data.Linq.Table<KeywordForLink> o, int id)
        {
            return o.Any(p => p.Id == id);
        }

        /// <summary>
        /// 验证指定的是否已经存在。
        /// </summary>
        /// <param name="id">验证的标识 Id。</param>
        /// <returns>布尔值表示指定的是否已经存在。</returns>
        public static bool Exists(int id)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            dc.ObjectTrackingEnabled = false;
            return dc.KeywordForLinks.Exists(id);
        }

        public static bool Exist(string keyword, int? siteId)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            dc.ObjectTrackingEnabled = false;

            return dc.KeywordForLinks.Any(p => p.Keyword == keyword && p.SiteId == siteId);
        }
        #endregion
    }



    /// <summary>
    /// KeywordForLinks 类操作部分。
    /// </summary>
    public static partial class KeywordForLinks
    {
        #region Insert
        /// <summary>
        /// 添加。
        /// </summary>
        /// <param name="insertedKeywordForLink">添加的。</param>
        /// <returns>添加的。</returns>
        public static KeywordForLink Insert(KeywordForLink insertedKeywordForLink)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();

            if (Exist(insertedKeywordForLink.Keyword, insertedKeywordForLink.SiteId))
            {
                throw new ObjectExistsException(Res.KeywordLink_IsExists);
            }

            KeywordForLink keywordForLink = insertedKeywordForLink.ToNewEntity<KeywordForLink>();
            keywordForLink.CreatorId = Users.CurrentUserId;
            keywordForLink.CreationDate = DateTime.Now;
            //keywordForLink.IsDelete = false;

            GetInsertRight(dc, keywordForLink, true);	// 权限验证

            dc.KeywordForLinks.InsertOnSubmit(keywordForLink);
            dc.SubmitChanges();

            // 持久化资源
            //InfoItems.SetPersistent(dc, keywordForLink.GlobalId, true);

            // 记录日志
            Logs.Insert(dc, ResourceId, (int)PermissionCode.Insert, INFO_TYPE, keywordForLink.Id.ToString(), PermissionCode.Insert.ToString(), keywordForLink.Keyword);

            // 返回只读数据
            return insertedKeywordForLink.FillByEntity(keywordForLink);
        }
        #endregion



        #region Update
        private static readonly HashSet<string> _updatedExcludeColumns = typeof(KeywordForLink).GetEntityColumnNames(new string[] {
				"Id","CreatorId","CreationDate","SiteId"	// 在这里填写更新的排除列
			}, true);

        /// <summary>
        /// 修改。
        /// </summary>
        /// <param name="updatedKeywordForLink">修改的。</param>
        /// <returns>修改的。</returns>
        public static KeywordForLink Update(KeywordForLink updatedKeywordForLink)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();

            KeywordForLink keywordForLink = dc.KeywordForLinks.GetItem(updatedKeywordForLink.Id);
            if (keywordForLink == null)
                throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

            GetUpdateRight(dc, keywordForLink, true);	// 权限验证

            keywordForLink.FillByEntity(updatedKeywordForLink, EntityColumnsSetType.Exclude, _updatedExcludeColumns);

            try
            {
                dc.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
            catch (ChangeConflictException e)
            {
                foreach (ObjectChangeConflict occ in dc.ChangeConflicts)
                {
                    occ.Resolve(RefreshMode.KeepCurrentValues);
                }
            }

            // 持久化资源
            //InfoItems.SetPersistent(dc, keywordForLink.GlobalId, true);

            // 记录日志
            Logs.Insert(dc, ResourceId, (int)PermissionCode.Update, INFO_TYPE, keywordForLink.Id.ToString(), PermissionCode.Update.ToString(), keywordForLink.Keyword);

            // 返回只读数据
            return updatedKeywordForLink.FillByEntity(keywordForLink);
        }
        #endregion


        #region Delete
        /// <summary>
        /// 删除。
        /// </summary>
        /// <param name="id">删除的标识 Id。</param>
        public static void Delete(int id)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();

            KeywordForLink keywordForLink = dc.KeywordForLinks.GetItem(id);
            if (keywordForLink == null)
                throw new ObjectNotExistsException(Res.Operation_ObjectNotExists);

            GetDeleteRight(dc, keywordForLink, true);	// 权限验证

            Delete(dc, keywordForLink);

            dc.SubmitChanges();

            // 记录日志
            Logs.Insert(dc, ResourceId, (int)PermissionCode.Delete, INFO_TYPE, keywordForLink.Id.ToString(), PermissionCode.Delete.ToString(), keywordForLink.Keyword);
        }

        #region internal Delete
        internal static void Delete(GenericModuleDataContext dc, KeywordForLink keywordForLink)
        {
            dc.KeywordForLinks.DeleteOnSubmit(keywordForLink);

            // 删除资源
            //InfoItem infoItem = dc.InfoItems.GetItem(keywordForLink.GlobalId);
            //if (infoItem != null)
            //    InfoItems.Delete(dc, infoItem);
        }
        #endregion
        #endregion
    }



    /// <summary>
    /// KeywordForLinks 类对应操作权限部分。
    /// </summary>
    public static partial class KeywordForLinks
    {
        #region GetInsertRight
        /// <summary>
        /// 获取当前用户是否有添加的权限。
        /// </summary>
        /// <param name="dc">数据容器。</param>
        /// <param name="keywordForLink">添加的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有添加的权限。</returns>
        public static bool GetInsertRight(GenericModuleDataContext dc, KeywordForLink keywordForLink, bool triggerException)
        {
            string userName = Users.CurrentUserName;
            int permissionCode = (int)PermissionCode.Insert;
            bool b = dc.AccessController.GetUserIsHasPermission<KeywordForLink>(userName, keywordForLink, ResourceId, permissionCode);

            if (triggerException && !b)
                throw new PermissionException(userName, keywordForLink, ResourceId, permissionCode, Res.PermissionExceptionMessage);
            return b;
        }

        /// <summary>
        /// 获取当前用户是否有添加的权限。
        /// </summary>
        /// <param name="keywordForLink">添加的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有添加的权限。</returns>
        public static bool GetInsertRight(KeywordForLink keywordForLink, bool triggerException)
        {
            return GetInsertRight(new GenericModuleDataContext(), keywordForLink, triggerException);
        }

        /// <summary>
        /// 获取当前用户是否有添加的权限。
        /// </summary>
        /// <param name="keywordForLink">添加的对象。</param>
        /// <returns>布尔值表示当前用户是否有添加的权限。</returns>
        public static bool GetInsertRight(KeywordForLink keywordForLink)
        {
            return GetInsertRight(keywordForLink, false);
        }
        #endregion



        #region GetUpdateRight
        /// <summary>
        /// 获取当前用户是否有更新的权限。
        /// </summary>
        /// <param name="dc">数据容器。</param>
        /// <param name="keywordForLink">更新的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有更新的权限。</returns>
        public static bool GetUpdateRight(GenericModuleDataContext dc, KeywordForLink keywordForLink, bool triggerException)
        {
            string userName = Users.CurrentUserName;
            int permissionCode = (int)PermissionCode.Update;
            bool b = dc.AccessController.GetUserIsHasPermission<KeywordForLink>(userName, keywordForLink, ResourceId, permissionCode);

            if (triggerException && !b)
                throw new PermissionException(userName, keywordForLink, ResourceId, permissionCode, Res.PermissionExceptionMessage);
            return b;
        }

        /// <summary>
        /// 获取当前用户是否有更新的权限。
        /// </summary>
        /// <param name="keywordForLink">更新的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有更新的权限。</returns>
        public static bool GetUpdateRight(KeywordForLink keywordForLink, bool triggerException)
        {
            return GetUpdateRight(new GenericModuleDataContext(), keywordForLink, triggerException);
        }

        /// <summary>
        /// 获取当前用户是否有更新的权限。
        /// </summary>
        /// <param name="keywordForLink">更新的对象。</param>
        /// <returns>布尔值表示当前用户是否有更新的权限。</returns>
        public static bool GetUpdateRight(KeywordForLink keywordForLink)
        {
            return GetUpdateRight(keywordForLink, false);
        }
        #endregion


        #region GetDeleteRight
        /// <summary>
        /// 获取当前用户是否有删除的权限。
        /// </summary>
        /// <param name="dc">数据容器。</param>
        /// <param name="keywordForLink">删除的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有删除的权限。</returns>
        public static bool GetDeleteRight(GenericModuleDataContext dc, KeywordForLink keywordForLink, bool triggerException)
        {
            string userName = Users.CurrentUserName;
            int permissionCode = (int)PermissionCode.Delete;
            bool b = dc.AccessController.GetUserIsHasPermission<KeywordForLink>(userName, keywordForLink, ResourceId, permissionCode);

            if (triggerException && !b)
                throw new PermissionException(userName, keywordForLink, ResourceId, permissionCode, Res.PermissionExceptionMessage);
            return b;
        }

        /// <summary>
        /// 获取当前用户是否有删除的权限。
        /// </summary>
        /// <param name="keywordForLink">删除的对象。</param>
        /// <param name="triggerException">当未通过权限验证的时候是否引发异常。</param>
        /// <returns>布尔值表示当前用户是否有删除的权限。</returns>
        public static bool GetDeleteRight(KeywordForLink keywordForLink, bool triggerException)
        {
            return GetDeleteRight(new GenericModuleDataContext(), keywordForLink, triggerException);
        }

        /// <summary>
        /// 获取当前用户是否有删除的权限。
        /// </summary>
        /// <param name="keywordForLink">删除的对象。</param>
        /// <returns>布尔值表示当前用户是否有删除的权限。</returns>
        public static bool GetDeleteRight(KeywordForLink keywordForLink)
        {
            return GetDeleteRight(keywordForLink, false);
        }
        #endregion
    }



    /// <summary>
    /// KeywordForLinks 类后台管理部分。
    /// </summary>
    public static partial class KeywordForLinks
    {
        public static bool GetManageListRight()
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            return dc.AccessController.GetUserIsHasPermission<object>(Users.CurrentUserName, null, KeywordForLinks.ResourceId, (int)KeywordForLinks.PermissionCode.Update, Sites.CurrentSiteId);
        }

		public static bool GetManageListRight(int? siteId)
		{
			GenericModuleDataContext dc = new GenericModuleDataContext();
			return dc.AccessController.GetUserIsHasPermission<object>(Users.CurrentUserName, null, KeywordForLinks.ResourceId, (int)KeywordForLinks.PermissionCode.Update, siteId);
		}




        public struct KeywordForLinkForManageList
        {
            public int Id { get; set; }
            public string Keyword { get; set; }
            public string LinkUrl{get;set;}
            public int Count{get;set;}
            public DateTime CreateDate { get; set; }
            public int? SiteId { get; set; }
        }

        public static PaginationInfo<List<KeywordForLinkForManageList>> GetPaginationManageList(int? siteId, string keyword, int pageSize, int currentPage)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            dc.ObjectTrackingEnabled = false;

            var q = from p in dc.KeywordForLinks
                    select new KeywordForLinkForManageList { Id = p.Id,Keyword=p.Keyword,Count=p.Count,CreateDate=p.CreationDate,LinkUrl=p.LinkUrl,SiteId=p.SiteId/* 这里填写管理列表列设置 */ };

            if (!string.IsNullOrEmpty(keyword))
                q = q.Where(p => p.Keyword.Contains(keyword));

            if (siteId.HasValue)
            {
                q = q.Where(p => p.SiteId == siteId.Value);
            }

            PaginationInfo<List<KeywordForLinkForManageList>> pageInfo = new PaginationInfo<List<KeywordForLinkForManageList>>();
            pageInfo.PageSize = pageSize;
            pageInfo.CurrentPage = currentPage;
            pageInfo.RecordCount = q.Count();
            pageInfo.Records = q.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            return pageInfo;
        }

        public struct KeywordForLinkList
        {
            public string Keyword{get;set;}
            public string LinkUrl{get;set;}
            public int Count { get; set; }
            public int? SiteId { get; set; }
        }

        public static List<KeywordForLinkList> GetList(int? siteId)
        {
            GenericModuleDataContext dc = new GenericModuleDataContext();
            dc.ObjectTrackingEnabled = false;

            IQueryable<KeywordForLinkList> q;

            if (siteId.HasValue)
            {
                q = from p in dc.KeywordForLinks
                    where p.SiteId == siteId.Value || p.SiteId == null
                    select new KeywordForLinkList { Keyword = p.Keyword, LinkUrl = p.LinkUrl, Count = p.Count,SiteId=p.SiteId };
            }
            else
            {
                q = from p in dc.KeywordForLinks
                    where p.SiteId == null
                    select new KeywordForLinkList { Keyword = p.Keyword, LinkUrl = p.LinkUrl, Count = p.Count };
            }
            List<KeywordForLinkList> list = q.ToList();
            list = list.OrderByDescending(p => p.SiteId).ToList();
            list = list.Distinct(new KeywordComparer()).ToList();
            return list;
        }
    }

    public class KeywordComparer : IEqualityComparer<KeywordForLinks.KeywordForLinkList>
    {

        #region IEqualityComparer<KeywordForLinkList> 成员

        public bool Equals(KeywordForLinks.KeywordForLinkList x, KeywordForLinks.KeywordForLinkList y)
        {
            if (x.Keyword.Equals(y.Keyword))
            {
                return true;
            }
            return false;
        }

        public int GetHashCode(KeywordForLinks.KeywordForLinkList obj)
        {
            return obj.Keyword.GetHashCode();
        }

        #endregion
    }
}